#! /usr/bin/env python
#coding=utf-8


from get_month_quarter import *

db = get_db_connection()


#--------------------每日风险点状态更新开始--------------------#
def update_risksolution_tasks_develop_status_run():
    
    #从settings.ini获取任务类型编号
    #settings = Ini('../apps/settings.ini')
    Tasks_develop = get_model('tasks_develop')
    Risksolution = get_model('risksolution')
    
    Risksolution.modified_user.default =None
    #更新风险整改措施中关联任务已被删除的任务
    db.begin()
    sr_sel=Risksolution.filter(and_(Risksolution.c.solution_mode == '1',
                             Risksolution.c.task_id != None,
                            ~Risksolution.c.task_id.in_(
                                                select([Tasks_develop.c.id]))))
    
    for sr_obj in sr_sel:
        sr_obj.task_id=None
        sr_obj.save()
    db.commit()
    
    #更新开发模式解决的整改措施状态
    sel=select([Risksolution.c.id,Tasks_develop.c.stage,Risksolution.c.nondev_riskpoint_status],
                        and_(Risksolution.c.solution_mode == '1',
                             Risksolution.c.task_id != None,
                             Tasks_develop.c.id == Risksolution.c.task_id))
                                                
    rs_sel=sel.execute()
    for row in rs_sel:
        Risksolution_id,task_stage,nondev_riskpoint_status=row
        #将开发任务状态转换为对应整改措施状态
        if task_stage and task_stage=='00':
            Risksolution_status='1'
        elif task_stage and task_stage=='FN':
            Risksolution_status='F'
        else:
            Risksolution_status='2'
        
        #更新整改措施状态   
        if nondev_riskpoint_status and nondev_riskpoint_status==Risksolution_status:
#           print '__----------------',nondev_riskpoint_status,Risksolution_status
           pass
        else:
            do_(Risksolution.table.update(Risksolution.c.id == Risksolution_id).values(nondev_riskpoint_status=Risksolution_status))
#            print '+++++++++',nondev_riskpoint_status,Risksolution_status
    non_taks_sel = Risksolution.filter(and_(Risksolution.c.solution_mode == '1',
                        Risksolution.c.task_id == None))
    for row in non_taks_sel:
        if row:
            row.nondev_riskpoint_status='N'
            row.save()
    
        
if __name__ == '__main__':
    try:
        db.begin()
        update_risksolution_tasks_develop_status_run()
        db.commit()
        log.info("finish")
    except Exception, e:
        db.rollback()
        log.exception(e)
        log.error('error')
        raise


